package com.atomdayl.domain.therecipe;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.EditorInfo;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.atomdayl.domain.therecipe.activity.BaseActivity;
import com.atomdayl.domain.therecipe.activity.ChangePasswordActivity;
import com.atomdayl.domain.therecipe.activity.RegisterActivity;
import com.atomdayl.domain.therecipe.dummy.UserModel;
import com.atomdayl.domain.therecipe.network.RequestBuildManager;
import com.atomdayl.domain.therecipe.network.ThreadCallback;
import com.atomdayl.domain.therecipe.network.ThreadManager;
import com.atomdayl.domain.therecipe.utils.PreferencesUtils;

/**
 * A login screen that offers login via email/password.
 */
public class LoginActivity extends BaseActivity implements ThreadCallback{


    // UI references.
    private AutoCompleteTextView mEmailView;
    private EditText mPasswordView;
    private View mProgressView;
    private View mLoginFormView;
    private Button mRegisterBtn;
    private Button mChangePasswordBtn;
    private int taskId = 1 << 5;
    private boolean isLog;
    private String mUsername;
    private String mPassword;
    private CheckBox mSaveLoginBox;
    private boolean isSaveLogin;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        // Set up the login form.
        mEmailView = (AutoCompleteTextView) findViewById(R.id.email);
        mPasswordView = (EditText) findViewById(R.id.password);
        mSaveLoginBox = (CheckBox) findViewById(R.id.check_save_login);
        mPasswordView.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView textView, int id, KeyEvent keyEvent) {
                if (id == R.id.login || id == EditorInfo.IME_NULL) {
//                    attemptLogin();
                    return true;
                }
                return false;
            }
        });
        mRegisterBtn = (Button) findViewById(R.id.login_register_btn);
        mChangePasswordBtn = (Button) findViewById(R.id.login_change_password_btn);

        mChangePasswordBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, ChangePasswordActivity.class);
                startActivity(intent);
            }
        });

        mRegisterBtn.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
            }
        });

        Button mEmailSignInButton = (Button) findViewById(R.id.email_sign_in_button);
        assert mEmailSignInButton != null;
        mEmailSignInButton.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                if(isLog) return ;
                String emailStr = mEmailView.getText().toString().trim();
                String passwordStr = mPasswordView.getText().toString().trim();
                login(emailStr, passwordStr);
            }
        });

        mLoginFormView = findViewById(R.id.login_form);
        mProgressView = findViewById(R.id.login_progress);

        obtionUser();
    }

    private void obtionUser() {
        UserModel user = PreferencesUtils.getUser(this);
        if(user != null && !TextUtils.isEmpty(user.getUsername()) && !TextUtils.isEmpty(user.getPassword())) {
            mEmailView.setText(user.getUsername());
            mPasswordView.setText(user.getPassword());
            login(user.getUsername(), user.getPassword());
        }
    }

    private void login(String email, String password) {
        if(TextUtils.isEmpty(email) || TextUtils.isEmpty(password)) {
            Toast.makeText(this, "账号密码不能为空", Toast.LENGTH_LONG).show();
            return ;
        }

        if(verifyLogin(email, password)) {
            String logUrl = RequestBuildManager.getInstance().buildLoginRequest(email, password);
            mUsername = email;
            mPassword = password;
            isSaveLogin = mSaveLoginBox.isChecked();
            ThreadManager.getInstance().exeGetTask(this, this, taskId, logUrl, false, true);

            isLog = true;
        }
    }

    private boolean verifyLogin(String email, String password) {
        /**
         * 文档标注是需要有@字符，但不知道是否是一定需要邮箱的格式，、
         * 我目前使用简单粗暴的方式做（校验email是否包含@字符，如果要使用标准邮箱格式的话将这个地方替换成邮箱校验的正则表达式。网上一大堆随便搜一个就可以了）
         */

        if(!email.contains("@")){
            Toast.makeText(this, "用户名格式不正确，请输入邮箱格式", Toast.LENGTH_SHORT).show();
            return false;
        }
        //这段可以设置下
//        if(password.length() < 6) {
//            Toast.makeText(this, "请输入大于6位的密码", Toast.LENGTH_SHORT).show();
//            return false;
//        }
        return true;
    }

    @Override
    public void onCallbackSucceedFromThread(String resultData, int taskId) {
        Toast.makeText(this, resultData, Toast.LENGTH_SHORT).show();
        if(isSaveLogin) {
            UserModel userModel = new UserModel();
            userModel.setName(resultData);
            userModel.setUsername(mUsername);
            userModel.setPassword(mPassword);
            PreferencesUtils.saveUser(this, userModel);
        }
    }

    @Override
    public void onCallbackFailureFromThread(String resultDate, int taskId) {
        Toast.makeText(this, "登陆接口连接失败", Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onCancelFromThread(String msg, int taskId) {

    }
}

